package com.ruoyi.common.utils;

import java.io.IOException;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

public class DesUtil {
    private static final String DES = "DES";

    private static final String ENCODE = "UTF-8";

    private static final byte[] ivByte = new byte[]{1, 2, 3, 4, 5, 6, 7, 8};

    public static final String CIPHER_ALGORITHM = "DES/CBC/PKCS5Padding";

    public static String apikey = "5e29f483c48848";

    public static String key = Md5Util.md5Hex(apikey);

    public static void main(String[] args) throws Exception {
        String data = "123456";
        String timeSend = "1536313412";
        String apikey = "5e29f483c48848";
        String messageId = "cdf5157133f64b409e69d60c4329bb72";
        String key = Md5Util.md5Hex(apikey);
        try {
            String encrypt = encrypt(data, key);
            System.out.println(encrypt);
            System.out.println(decrypt(encrypt, key));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String encrypt(String data, String key) throws Exception {
        byte[] bt = encrypt(data.getBytes("UTF-8"), key.getBytes("UTF-8"));
        return new String(Base64.getEncoder().encode(bt));
    }

    public static String decrypt(String data, String key) throws Exception {
        if (data == null) {
            return null;
        }
        byte[] buf = Base64.getDecoder().decode(data);
        byte[] bt = decrypt(buf, key.getBytes("UTF-8"));
        return new String(bt, "UTF-8");
    }

    private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
        IvParameterSpec iv = new IvParameterSpec(ivByte);
        DESKeySpec dks = new DESKeySpec(key);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey securekey = keyFactory.generateSecret(dks);
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(1, securekey, iv);
        return cipher.doFinal(data);
    }

    private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
        IvParameterSpec iv = new IvParameterSpec(ivByte);
        DESKeySpec dks = new DESKeySpec(key);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey securekey = keyFactory.generateSecret(dks);
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(2, securekey, iv);
        return cipher.doFinal(data);
    }
}
